Page({
  data: {
    baseURL:'http://node3-cn-hz-cu.haoyue.ltd:10086',
    // 上课周期数据（重构为对象数组）
    weekdays: [
      { name: '周一', value: 'monday', selected: false },
      { name: '周二', value: 'tuesday', selected: false },
      { name: '周三', value: 'wednesday', selected: false },
      { name: '周四', value: 'thursday', selected: false },
      { name: '周五', value: 'friday', selected: false },
      { name: '周六', value: 'saturday', selected: false },
      { name: '周日', value: 'sunday', selected: false }
    ],
    // 科目列表（重构为对象数组）
    subjects: [
      {name: '语文', selected: false},
      {name: '数学', selected: false},
      {name: '英语', selected: false},
      {name: '物理', selected: false},
      {name: '化学', selected: false},
      {name: '生物', selected: false},
      {name: '历史', selected: false},
      {name: '地理', selected: false},
      {name: '政治', selected: false},
      {name: '编程', selected: false},
      {name: '美术', selected: false},
      {name: '音乐', selected: false},
      {name: '其他', selected: false, isOther: true}
    ],
    otherSubject: '', // 存储其他科目输入
    otherInputDisabled: true, // 其他科目输入框禁用状态
    isOtherSelected: false, // 是否选中了其他
    // 学习目标数据
    goalOptions: [
      { name: '短期提分（应对考试）', value: 'score', selected: false },
      { name: '培养学习兴趣', value: 'interest', selected: false },
      { name: '巩固基础知识', value: 'foundation', selected: false },
      { name: '竞赛/特长备战', value: 'competition', selected: false }
    ],
    
    // 偏好学习方式数据
    methodOptions: [
      { name: '习题讲解为主', value: 'question', selected: false },
      { name: '知识点系统讲授', value: 'lecture', selected: false },
      { name: '互动游戏式教学', value: 'interaction', selected: false },
      { name: '大量练习巩固', value: 'practice', selected: false }
    ],
    
    // 表单数据
    formData: {
      childName: '',
      childGrade: '',
      subjects: [], // 存储选中的科目
      address: '',
      classDuration: '',
      weekdays: [],
      classTime: '',
      classEndTime: '',
      salary: '',
      goal: '',
      scores: '',
      teacherReq: '',
      genderPreference: '',
      classFrequency: '',
      attention: '' // 注意力时长
    },
    
    // UI状态
    scoreCount: 0,
    reqCount: 0,
    maxScoreLength: 500,
    maxReqLength: 500,
    maxGoalLength: 500,
    
    // 选项数据
    frequencyOptions: [
      { name: '每周1次', value: 'once' },
      { name: '每周2次', value: 'twice' },
      { name: '每周3次', value: 'three' },
      { name: '每周4次及以上', value: 'more' }
    ],
    genderOptions: [
      { name: '不限', value: '' },
      { name: '男老师', value: 'male' },
      { name: '女老师', value: 'female' }
    ],
    durationOptions: [
      { name: '45分钟', value: '45' },
      { name: '1小时', value: '60' },
      { name: '1.5小时', value: '90' },
      { name: '2小时', value: '120' }
    ],
    goalOptions: [
      { name: '短期提分（应对考试）', value: 'score' },
      { name: '培养学习兴趣', value: 'interest' },
      { name: '巩固基础知识', value: 'foundation' },
      { name: '竞赛/特长备战', value: 'competition' }
    ],
    methodOptions: [
      { name: '习题讲解为主', value: 'question' },
      { name: '知识点系统讲授', value: 'lecture' },
      { name: '互动游戏式教学', value: 'interaction' },
      { name: '大量练习巩固', value: 'practice' }
    ],
    attentionOptions: [
      { name: '20分钟内', value: '20' },
      { name: '30分钟内', value: '30' },
      { name: '45分钟内', value: '45' },
      { name: '60分钟以上', value: '60' }
    ]
  },
  // 切换星期选择
  toggleWeekday(e) {
    const index = e.currentTarget.dataset.index;
    const weekdays = [...this.data.weekdays];
    const weekday = weekdays[index];
    
    // 切换选中状态
    weekday.selected = !weekday.selected;
    
    // 更新数据
    this.setData({ weekdays });
    
    // 提取选中的值
    const selectedWeekdays = weekdays
      .filter(item => item.selected)
      .map(item => item.value);
    
    // 更新表单数据
    this.setData({
      'formData.weekdays': selectedWeekdays
    });
  },

  // 科目选择
  toggleSubject(e) {
    const index = e.currentTarget.dataset.index;
    const subjects = [...this.data.subjects];
    const subject = subjects[index];
    
    // 检查当前选中状态
    const currentState = subject.selected;
    
    // 计算当前已选中的科目数量
    const selectedCount = subjects.filter(item => item.selected).length;
    
    // 如果是取消选中
    if (currentState) {
      subject.selected = false;
      
      // 如果是取消选中"其他"科目
      if (subject.isOther) {
        this.setData({
          subjects,
          otherSubject: '',
          otherInputDisabled: true,
          isOtherSelected: false
        });
        return;
      }
      
      this.setData({ 
        subjects,
        isOtherSelected: subjects.some(item => item.isOther && item.selected)
      });
      return;
    }
    
    // 如果是选中操作，检查是否超过限制
    if (selectedCount >= 5) {
      wx.showToast({
        title: '最多选择5个科目',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 更新选中状态
    subject.selected = true;
    
    // 如果是选中"其他"科目
    if (subject.isOther) {
      this.setData({
        subjects,
        otherInputDisabled: false,
        isOtherSelected: true
      });
      return;
    }
    
    this.setData({ 
      subjects,
      isOtherSelected: subjects.some(item => item.isOther && item.selected)
    });
  },

  // 其他科目输入
  bindOtherSubjectInput(e) {
    this.setData({ otherSubject: e.detail.value });
  },

  // 文本输入处理
  onInputChange(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`formData.${field}`]: value
    });
    
    // 字数统计
    if (field === 'scores') {
      this.setData({ scoreCount: value.length });
    } else if (field === 'teacherReq') {
      this.setData({ reqCount: value.length });
    }
  },

  // 单选选择处理
  onRadioChange(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 多选选择处理
  onCheckboxChange(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 时间选择处理
onTimeChange: function(e) {
  const field = e.currentTarget.dataset.field;
  const value = e.detail.value;
  
  // 验证时间格式
  if (!/^\d{2}:\d{2}$/.test(value)) {
    wx.showToast({
      title: '时间格式不正确',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 更新数据
  this.setData({
    [`formData.${field}`]: value
  });
  
  // 实时验证时间逻辑
  if (field === 'classTime' && this.data.formData.classEndTime) {
    this.validateTimeOrder();
  }
  if (field === 'classEndTime' && this.data.formData.classTime) {
    this.validateTimeOrder();
  }
},

// 验证时间顺序
validateTimeOrder: function() {
  const { classTime, classEndTime } = this.data.formData;
  if (classTime && classEndTime && classTime >= classEndTime) {
    wx.showToast({
      title: '开始时间需早于结束时间',
      icon: 'none',
      duration: 1500
    });
    return false;
  }
  return true;
},

  // 验证时间顺序
  validateTimeOrder: function() {
    const { classTime, classEndTime } = this.data.formData;
    if (classTime && classEndTime && classTime >= classEndTime) {
      wx.showToast({
        title: '开始时间需早于结束时间',
        icon: 'none',
        duration: 1500
      });
      return false;
    }
    return true;
  },

  // 切换学习目标选择
  toggleGoal(e) {
    const index = e.currentTarget.dataset.index;
    const goalOptions = [...this.data.goalOptions];
    const goal = goalOptions[index];
    
    // 切换选中状态
    goal.selected = !goal.selected;
    
    // 更新数据
    this.setData({ goalOptions });
    
    // 提取选中的值
    const selectedGoals = goalOptions
      .filter(item => item.selected)
      .map(item => item.value);
    
    // 更新表单数据
    this.setData({
      'formData.goal': selectedGoals
    });
  },
  
  // 切换学习方法选择
  toggleMethod(e) {
    const index = e.currentTarget.dataset.index;
    const methodOptions = [...this.data.methodOptions];
    const method = methodOptions[index];
    
    // 切换选中状态
    method.selected = !method.selected;
    
    // 更新数据
    this.setData({ methodOptions });
    
    // 提取选中的值
    const selectedMethods = methodOptions
      .filter(item => item.selected)
      .map(item => item.value);
    
    // 更新表单数据
    this.setData({
      'formData.method': selectedMethods
    });
  },

  // 保存草稿
  saveDraft() {
    // 提取选中的科目（包括其他科目输入）
    let selectedSubjects = this.data.subjects
      .filter(item => item.selected && !item.isOther)
      .map(item => item.name);
    if (this.data.isOtherSelected && this.data.otherSubject.trim()) {
      selectedSubjects.push(this.data.otherSubject.trim());
    }
    
    const formData = {
      ...this.data.formData,
      subjects: selectedSubjects,
      otherSubject: this.data.otherSubject
    };
    
    // 保存到本地存储
    wx.setStorageSync('orderDraft', {
      data: formData,
      time: new Date().toLocaleString(),
      timestamp: new Date().getTime()
    });

    wx.showToast({
      title: '草稿已保存',
      icon: 'success',
      duration: 2000
    });
  },

  // 表单提交
formSubmit: function() {
  // 1. 收集科目数据
  let selectedSubjects = this.data.subjects
    .filter(item => item.selected && !item.isOther)
    .map(item => item.name);
  
  // 添加其他科目
  if (this.data.isOtherSelected && this.data.otherSubject.trim()) {
    selectedSubjects.push(this.data.otherSubject.trim());
  }
  
  // 2. 收集星期数据
  const selectedWeekdays = this.data.weekdays
    .filter(item => item.selected)
    .map(item => item.value);
  
  // 3. 收集学习目标数据
  const selectedGoals = this.data.goalOptions
    .filter(item => item.selected)
    .map(item => item.value);
  
  // 4. 收集学习方法数据
  const selectedMethods = this.data.methodOptions
    .filter(item => item.selected)
    .map(item => item.value);
  
  // 5. 准备提交数据
  const formData = {
    ...this.data.formData,
    subjects: selectedSubjects,
    weekdays: selectedWeekdays,
    goal: selectedGoals,
    method: selectedMethods,
    submitTime: new Date().toISOString(),
    user_id: 2
  };
  
  // 6. 验证必填项
  const requiredFields = [
    { field: 'childName', name: '孩子姓名' },
    { field: 'childGrade', name: '年龄/年级' },
    { field: 'subjects', name: '辅导科目' },
    { field: 'address', name: '授课地址' },
    { field: 'classDuration', name: '每节课时长' },
    { field: 'weekdays', name: '上课周期' },
    { field: 'classTime', name: '上课开始时间' },
    { field: 'classEndTime', name: '上课结束时间' },
    { field: 'goal', name: '学习目标' },
    { field: 'attention', name: '注意力时长' }
  ];
  
  const missingFields = [];
  requiredFields.forEach(item => {
    const value = formData[item.field];
    if (!value || (Array.isArray(value) && value.length === 0)) {
      missingFields.push(item.name);
    }
  });
  
  // 7. 验证薪资 - 单独处理，因为需要特殊验证
  let salaryError = null;
  if (!formData.salary) {
    missingFields.push('薪资标准');
  } else {
    // 尝试转换为数字
    const salaryValue = parseFloat(formData.salary);
    
    // 检查是否为有效数字
    if (isNaN(salaryValue)) {
      salaryError = '薪资必须为数字';
    }
    // 检查范围
    else if (salaryValue < 40 || salaryValue > 1000) {
      salaryError = '薪资范围建议40-1000元/小时';
    }
  }
  
  // 8. 验证科目数量
  if (selectedSubjects.length === 0) {
    missingFields.push('请至少选择1个辅导科目');
  } else if (selectedSubjects.length > 5) {
    wx.showToast({
      title: '辅导科目最多选择5个',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  
  // 9. 验证孩子姓名格式
  if (formData.childName && (formData.childName.length < 2 || formData.childName.length > 10)) {
    wx.showToast({
      title: '孩子姓名请输入2-10个字',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  
  // 10. 验证时间顺序
  if (!this.validateTimeOrder()) {
    return;
  }
  
  // 11. 验证学习目标
  if (selectedGoals.length === 0) {
    missingFields.push('请至少选择1个学习目标');
  }
  
  // 12. 处理薪资错误
  if (salaryError) {
    wx.showToast({
      title: salaryError,
      icon: 'none',
      duration: 2000
    });
    return;
  }
  
  // 13. 显示错误提示
  if (missingFields.length > 0) {
    wx.showModal({
      title: '信息不完整',
      content: `请完善以下信息：\n${missingFields.join('\n')}`,
      showCancel: false,
      confirmText: '知道了'
    });
    return;
  }
  
  // 14. 提交到服务器
  wx.showLoading({
    title: '发布中...',
    mask: true
  });
  
  wx.request({
    url: 'http://node3-cn-hz-cu.haoyue.ltd:10086/pushIntroduction-s',
    method: 'POST',
    header: {
      'content-type': 'application/json'
    },
    data: formData,
    success: (res) => {
      wx.hideLoading();
      if (res.statusCode === 200) {
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            // 清除草稿
            wx.removeStorageSync('orderDraft');
            // 返回上一页
            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          }
        });
      } else {
        wx.showToast({
          title: `发布失败：${res.data?.message || '服务器错误'}`,
          icon: 'none',
          duration: 3000
        });
      }
    },
    fail: (err) => {
      wx.hideLoading();
      wx.showToast({
        title: '网络请求失败，请重试',
        icon: 'none',
        duration: 3000
      });
      console.error('API请求失败:', err);
    }
  });
},

// 验证时间顺序
validateTimeOrder: function() {
  const { classTime, classEndTime } = this.data.formData;
  
  // 检查是否两个时间都已选择
  if (!classTime || !classEndTime) {
    return true; // 让必填项验证捕获错误
  }
  
  // 比较时间
  const startParts = classTime.split(':').map(Number);
  const endParts = classEndTime.split(':').map(Number);
  
  const startMinutes = startParts[0] * 60 + startParts[1];
  const endMinutes = endParts[0] * 60 + endParts[1];
  
  if (startMinutes >= endMinutes) {
    wx.showToast({
      title: '开始时间需早于结束时间',
      icon: 'none',
      duration: 2000
    });
    return false;
  }
  
  return true;
},

  // 生命周期函数
  onLoad: function(options) {
    const app = getApp(); // 获取全局应用实例
    // 读取草稿
    const draft = wx.getStorageSync('orderDraft');
    const sevenDays = 7 * 24 * 60 * 60 * 1000;
    
    if (draft && draft.data) {
      if (new Date().getTime() - draft.timestamp < sevenDays) {
        wx.showModal({
          title: '发现草稿',
          content: `是否加载上次保存的草稿（${draft.time}）？`,
          confirmText: '加载',
          cancelText: '新建',
          success: (res) => {
            if (res.confirm) {
              // 恢复科目选择状态
              const subjects = this.data.subjects.map(item => {
                if (item.isOther) {
                  const isOtherSelected = draft.data.subjects.some(sub => 
                    !this.data.subjects.some(s => s.name === sub && !s.isOther)
                  );
                  return { ...item, selected: isOtherSelected };
                }
                return { ...item, selected: draft.data.subjects.includes(item.name) };
              });
              
              // 提取其他科目内容
              let otherSubject = '';
              if (draft.data.subjects) {
                const otherSubjects = draft.data.subjects.filter(sub => 
                  !this.data.subjects.some(s => s.name === sub && !s.isOther)
                );
                if (otherSubjects.length > 0) {
                  otherSubject = otherSubjects[0];
                }
              }
              // 恢复星期选择状态
      const weekdays = this.data.weekdays.map(item => {
        const selected = draft.data.weekdays.includes(item.value);
        return { ...item, selected };
      });
      // 恢复学习目标选择状态
      const goalOptions = this.data.goalOptions.map(item => {
        const selected = draft.data.goal.includes(item.value);
        return { ...item, selected };
      });
      
      // 恢复学习方法选择状态
      const methodOptions = this.data.methodOptions.map(item => {
        const selected = draft.data.method.includes(item.value);
        return { ...item, selected };
      });
              
              this.setData({
                goalOptions,
                methodOptions,
                weekdays,
                formData: draft.data,
                subjects: subjects,
                otherSubject: otherSubject,
                otherInputDisabled: !subjects.find(item => item.isOther)?.selected,
                isOtherSelected: subjects.find(item => item.isOther)?.selected || false,
                scoreCount: (draft.data.scores || '').length,
                reqCount: (draft.data.teacherReq || '').length
              });
            }
          }
        });
      } else {
        wx.removeStorageSync('orderDraft');
      }
    }
  },

  onUnload: function() {
    // 自动保存草稿
    const formData = this.data.formData;
    const hasContent = Object.keys(formData).some(key => {
      const value = formData[key];
      return value !== '' && !(Array.isArray(value) && value.length === 0);
    });
    
    if (hasContent) {
      this.saveDraft();
    }
  }
});